import React, { useMemo, useState } from 'react';
import { View, StyleSheet } from 'react-native';
import {
    Layout,
    UI,
    useThemeColors,
    useDeviceInfo,
    DeviceInfoService,
} from '@gaozh1024/rn-toolkit';

const DeviceTestScreen: React.FC = () => {
    const colors = useThemeColors();
    const styles = StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', gap: 12 },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
    });

    // hook: 设备信息 + 刷新
    const { info, refresh } = useDeviceInfo();

    // service 独立测试状态
    const [lastInfo, setLastInfo] = useState<any | null>(null);
    const [deviceId, setDeviceId] = useState<string>(''); // getDeviceId
    const [appInfo, setAppInfo] = useState<{ version: string; buildNumber: string; bundleId: string } | null>(null);
    const [deviceType, setDeviceType] = useState<string>('');
    const [isTablet, setIsTablet] = useState<boolean | null>(null);
    const [isEmulator, setIsEmulator] = useState<boolean | null>(null);
    const [batteryInfo, setBatteryInfo] = useState<{ batteryLevel: number; isCharging: boolean; powerState: any } | null>(null);
    const [memoryInfo, setMemoryInfo] = useState<{ totalMemory: number; usedMemory: number; freeMemory: number } | null>(null);

    // 基础操作
    const onRefreshHook = async () => {
        await refresh();
    };
    const onGetDeviceInfo = async () => {
        const res = await DeviceInfoService.getDeviceInfo();
        setLastInfo(res);
    };
    const onClearCache = () => {
        DeviceInfoService.clearCache();
        setLastInfo(null);
    };

    // 单项功能
    const onGetDeviceId = async () => {
        const id = await DeviceInfoService.getDeviceId();
        setDeviceId(id);
    };
    const onGetAppInfo = async () => {
        const { version, buildNumber, bundleId } = await DeviceInfoService.getAppInfo();
        setAppInfo({ version, buildNumber, bundleId });
    };
    const onGetDeviceType = () => {
        const type = DeviceInfoService.getDeviceType();
        setDeviceType(type);
    };
    const onCheckTablet = async () => {
        const res = await DeviceInfoService.isTablet();
        setIsTablet(res);
    };
    const onCheckEmulator = async () => {
        const res = await DeviceInfoService.isEmulator();
        setIsEmulator(res);
    };
    const onGetBatteryInfo = async () => {
        const res = await DeviceInfoService.getBatteryInfo();
        setBatteryInfo(res);
    };
    const onGetMemoryInfo = async () => {
        const res = await DeviceInfoService.getMemoryInfo();
        setMemoryInfo(res);
    };

    return (
        <Layout.Page
            headerShown
            headerProps={{ title: 'Device 测试', backVisible: true }}
            padding={16}
            scrollable
            testID="DeviceTestScreen"
        >
            {/* Hook：设备信息展示与刷新 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>设备信息（hook）</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="刷新设备信息" onPress={onRefreshHook} testID="device-btn-refresh-hook" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>信息：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-brand">品牌：{info?.brand ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-model">型号：{info?.model ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-deviceId">设备ID：{info?.deviceId ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-system">系统：{info ? `${info.systemName} ${info.systemVersion}` : '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-app">
                            App：{info ? `${info.appVersion} (${info.buildNumber})` : '（未知）'}
                        </UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-bundle">BundleId：{info?.bundleId ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-screen">屏幕：{info ? `${info.screenWidth} x ${info.screenHeight}` : '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-platform">平台：{info?.platform ?? '（未知）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-tablet">平板：{String(info?.isTablet ?? '（未知）')}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-hook-emulator">模拟器：{String(info?.isEmulator ?? '（未知）')}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* Service：整体信息 + 缓存 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>完整信息 + 缓存</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="获取完整设备信息" onPress={onGetDeviceInfo} testID="device-btn-get-info" />
                        <UI.Button title="清除缓存" variant="outline" onPress={onClearCache} testID="device-btn-clear-cache" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>最近一次获取：</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-last-info">{lastInfo ? JSON.stringify(lastInfo) : '（空）'}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* Service：单项能力 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>单项能力</UI.Text>

                    {/* 设备ID / 应用信息 */}
                    <UI.Text color="text" style={{ marginTop: 4 }}>设备ID / 应用信息</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="获取设备ID" onPress={onGetDeviceId} testID="device-btn-get-id" />
                        <UI.Button title="获取应用信息" variant="outline" onPress={onGetAppInfo} testID="device-btn-get-app" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="body2" color="text" testID="device-text-id">设备ID：{deviceId || '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-app">
                            App：{appInfo ? `${appInfo.version} (${appInfo.buildNumber}) - ${appInfo.bundleId}` : '（空）'}
                        </UI.Text>
                    </View>

                    {/* 类型 / 平板 / 模拟器 */}
                    <UI.Text color="text" style={{ marginTop: 16 }}>类型 / 平板 / 模拟器</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="设备类型" onPress={onGetDeviceType} testID="device-btn-type" />
                        <UI.Button title="是否平板" variant="outline" onPress={onCheckTablet} testID="device-btn-tablet" />
                        <UI.Button title="是否模拟器" variant="outline" onPress={onCheckEmulator} testID="device-btn-emulator" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="body2" color="text" testID="device-text-type">设备类型：{deviceType || '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-tablet">平板：{String(isTablet)}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-emulator">模拟器：{String(isEmulator)}</UI.Text>
                    </View>

                    {/* 电池信息 */}
                    <UI.Text color="text" style={{ marginTop: 16 }}>电池信息</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="获取电池信息" onPress={onGetBatteryInfo} testID="device-btn-battery" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="body2" color="text" testID="device-text-battery-level">电量：{batteryInfo ? `${Math.round((batteryInfo.batteryLevel ?? 0) * 100)}%` : '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-battery-charging">充电中：{batteryInfo ? String(batteryInfo.isCharging) : '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-battery-state">电源状态：{batteryInfo?.powerState ? JSON.stringify(batteryInfo.powerState) : '（空）'}</UI.Text>
                    </View>

                    {/* 内存信息 */}
                    <UI.Text color="text" style={{ marginTop: 16 }}>内存信息</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="获取内存信息" onPress={onGetMemoryInfo} testID="device-btn-memory" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="body2" color="text" testID="device-text-memory-total">总内存：{memoryInfo ? `${memoryInfo.totalMemory}` : '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-memory-used">已使用：{memoryInfo ? `${memoryInfo.usedMemory}` : '（空）'}</UI.Text>
                        <UI.Text variant="body2" color="text" testID="device-text-memory-free">可用：{memoryInfo ? `${memoryInfo.freeMemory}` : '（空）'}</UI.Text>
                    </View>
                </Layout.Card>
            </View>
        </Layout.Page>
    );
};

export default DeviceTestScreen;